package com.situ.mall.base.service.impl;

import com.github.pagehelper.PageHelper;
import com.situ.mall.base.entity.*;
import com.situ.mall.base.mapper.*;
import com.situ.mall.base.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.base.service.IPayService;
import com.situ.mall.base.util.OrderSessionUtil;
import com.situ.mall.base.util.SnowFlake;
import com.situ.mall.base.vo.LayuiTableVO;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author darling
 * @since 2023-04-11
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private SnowFlake snowFlake;  // 雪花算法

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private MemberAddressMapper memberAddressMapper;

    @Autowired
    private IPayService payService;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    // 前端支付
    @Override
    @Transactional
    public Map<String, Object> saveOrder(String ids, Integer addId) {

        Map<String, Object> map = new HashMap<>();

        // 1.获取当前登录用户
        Member m = OrderSessionUtil.getCurrent();

        BigDecimal sumPrice = new BigDecimal(0);
        for (String cartId : ids.split(",")) {
            Cart cart = cartMapper.selectById(Integer.parseInt(cartId));
            Product p = productMapper.selectById(cart.getProductId());
            sumPrice = sumPrice.add(p.getPrice().multiply(BigDecimal.valueOf(cart.getCount())));
        }

        // 2.保存一个 order_info 数据
        OrderInfo order = new OrderInfo();
        order.setCreatetime(LocalDateTime.now());
        order.setMemberId(m.getId());
        order.setStatus(0);
        order.setPrice(sumPrice);

        // 雪花算法生成订单号
        order.setCode("Order-" + snowFlake.getNextId());
        order.setRemark("alipay");
        // 保存订单主表的数据
        baseMapper.insert(order);

        // 订单详情表
        for (String cartId : ids.split(",")) {
            OrderDetail orderDetail = new OrderDetail();
            Cart cart = cartMapper.selectById(Integer.parseInt(cartId));
            orderDetail.setAmount(cart.getCount());
            orderDetail.setProductId(cart.getProductId());
            orderDetail.setOrderId(cart.getId());
            orderDetailMapper.insert(orderDetail);
            // 删除购物车表
            cartMapper.deleteById(cartId);
        }

        // 用户地址档案
        MemberAddress ma = memberAddressMapper.selectById(addId);

        // 订单地址表
        OrderAddress oa = new OrderAddress();
        oa.setOrderId(order.getId());
        BeanUtils.copyProperties(ma, oa); // 从 ma 拷到 oa  属性拷贝
        oa.setId(null);
        orderAddressMapper.insert(oa);

        // 推送消息队列
        delaySend(new ActiveMQQueue("order.save"), order.getId(), 6000L);

        // 获取对应的支付信息
        String qrCode = payService.createPayOrder(order);
        map.put("qrCode", qrCode);
        map.put("order", order);
        return map;
    }

    private <T extends Serializable> void delaySend(Destination queue, T data, Long time) {
        Connection conn = null;
        Session session = null;
        MessageProducer producer = null;

        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        try {
            assert connectionFactory != null;
            conn = connectionFactory.createConnection();
            conn.start();
            session = conn.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //创建一个生产者
            producer = session.createProducer(queue);
            producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
            ObjectMessage message = session.createObjectMessage(data);
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
            producer.send(message);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (producer != null) {
                    producer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ignored) {

            }
        }
    }


    // 后台管理
    @Override
    public LayuiTableVO doList(Integer page, Integer limit, String keyword) {
        PageHelper.startPage(page, limit);
        return LayuiTableVO.data(baseMapper.doList(keyword));
    }

    @Override
    public LayuiTableVO orderList(Integer page, Integer limit) {
        return LayuiTableVO.data(baseMapper.orderList());
    }

    @Override
    public void UpdateStatus(String out_trade_no, int status) {

    }

    @Override
    public void updateStatusById(Integer id) {
        baseMapper.updateStatusById(id, 2);
    }

}
